package pswvclass.pswvandroid2.com.more.Wallet;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.Home;
import pswvclass.pswvandroid2.com.kwords.share.ShareKWordPayment;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HttpUtils;
import pswvclass.pswvandroid2.com.util.payment.OrderInfoUtil2_0;
import pswvclass.pswvandroid2.com.util.payment.PayResult;

/**
 */
public class Recharge extends AppCompatActivity implements View.OnClickListener{
    private String tag = "Recharge";
    private Button money_zhifubao_pay;
    private TextView money_munber;
    public static final String APPID = "2016092400586693";
    public static int shareKWordId;

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088102177083038";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "0.1";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCjpZpVulkYyIOX\n" +
            "HloS/hCGnLnz/w6W3an7rJ1Hb3hP19ksFCP7wEYO0QLYYF4s6clIlMoi/wZE/V8u\n" +
            "NB1QeGr4aPBQvlj9PNrTvJd028QbZjJZ15bJqIDrjLXoG3i1dahufUqEf8rhdBeb\n" +
            "1yTfiIL6glAAWpBjROD7A29AcoWVRNiQFO51vQ6CxhlLmdWnegAEOC4FYQ6+hXf9\n" +
            "5vJnYmvoTdAoufXjG3H3BWRufjEl0JuojvO+oVkLQ7tMh9dWiUAN/F6AnB/UC7RX\n" +
            "d4/l0dVaWyaTmKQIdNkogxI/h5wH+UE9QiVeNGEjEt1CWMyW1wbx85RjG6iH9V6F\n" +
            "w07xUSezAgMBAAECggEAJPSw9csvc7lUfjwMe12EveGG3OMsmEVWrc89dXRm5yEH\n" +
            "mjyyI5g4OgBZdCPPILVrD0kKnPyandnaNMTwGcwX3CFWo+VYk1e60zYzveAjWUyq\n" +
            "8j8NflzfQFJ2ggQyLkhz0P/aZDG3z1I4QqlDWnepnIjxKCNLmB9l70nHRfaW1C5r\n" +
            "XQMBdlI4ng+JYVfGO8zLfutuTvpG5WU+JAM+rKBZkrdOw8Vd4qkctddgDsz4o6W9\n" +
            "X7FpsrbludjQlB/dLfS+1By1eP6cUEh4toYw0CX///1XUZ5Nrzaz/yfm5LXJ0kas\n" +
            "pmTGuaUABXNIKFvqGDpW4nCUeBEbtcBgY9LX14TfAQKBgQDZVDpEbYwXC5DCoTYS\n" +
            "4LA+fRCivjgi0y1ocwB9nJ1IGlnYmbjs0ME5GwLtd8DcQ4pOFK4QhtjG7iMl4VkS\n" +
            "ZdJfNQLAkJ8C7XJZvq7Ic4Pgu7+3rXw7VRB957rvmB6z+Xt8H0iCF3aJwX8LLRfz\n" +
            "tQapMZmy5sKpir/kWq5bFXDNeQKBgQDAxAv0Cp5NzxNyDJ5NXqzY2YIXaeH4YQhL\n" +
            "KXU3WrNR+EgTUcTzWIcRTSHptgemhDSSrEEJVsUair+J2Qwm8ywAhXjCXuXGBK7J\n" +
            "CkYF4kXtUf3VCkTT2TtXRvD9oIxbUx5Ot0YSj1NmSJy33dTen1DL9M5GoQ9QPKdl\n" +
            "D+dc2OOPiwKBgQCyGWdCqm+SdyTjiw9wOvfTzdPzOmVwjJT6srvlNJJkA0w7yAYW\n" +
            "9CBUtwEYL/o5x5Ow1xuqaYd+xqrBIUJIZG8ZHK0rt5jH4mTCjRRZKukZI2NCmAZl\n" +
            "7Rj9xQiZzpTisoHyvwRBsA6xZ4PAWez2CBT0VLR7OsauAAmvjmyyMgjmKQKBgQCI\n" +
            "t0LHDfTiuJhRDjQEKb6refCzTGxxLdik/j1dSh3eaBouYZMvCD2bfroruOfKKP/k\n" +
            "evkRd5IJ1hgs21ysD1HI+OEB8i5C+DVC7t9k8uunerxtqX/RRMO6jd0D9Sc26keX\n" +
            "ipLPPQnohF1qZpHAZvv1+6WFIFvtC2ep3NK53jXfKwKBgQC4RBSyrMKuxWRq2mpT\n" +
            "kpQR5Bme0PYqNKJoM2Qqx/IXwi1yv9U0WVsluhy7mx/+EeIx+ITzIW4zOnOl5FP3\n" +
            "9NQyu0mZ5mRvlHlc8BZ11qhBGpXeDtijkk+wuzEEancvmiTM6cCGmlkgi1vUjigE\n" +
            "y4FeecZ9HfAkm1ZA3Oqy09V+Wg==";
    public static final String RSA_PRIVATE = "";
    private static final int PAY_SUCCESS = 3;
    private static final int SDK_PAY_FLAG = 2;
    protected static final int SUCCESS =1;
    protected static final int ERROR = 0;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.pswv_more_wallet_recharge);
        money_zhifubao_pay = (Button) findViewById(R.id.money_zhifubao_pay);
        money_zhifubao_pay.setOnClickListener(this);
        money_munber= (TextView) findViewById(R.id.money_munber);
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PAY_SUCCESS: {
                    Intent intent = new Intent();
                    intent.setClass(Recharge.this, Money.class);
                    startActivity(intent);
                    Toast.makeText(Recharge.this, "支付成功", Toast.LENGTH_SHORT).show();
                }
                break;
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        DBHelper db = new DBHelper(Recharge.this);
                        SQLiteDatabase sd = db.getWritableDatabase();
                        int userId = 0;
                        Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                        while (cursor.moveToNext()) {
                            userId = cursor.getInt(0);
                        }
                        cursor.close();
                        final int finalUserId = userId;
                        new Thread() {
                            @Override
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/myWalletAction/zhifubaoPaySuccess";
                                    final Map<String, String> map1 = new HashMap<String, String>();
                                    map1.put("userId", finalUserId + "");
                                    Log.v(tag,money_munber.getText().toString().trim());
                                    map1.put("moneyMunber", money_munber.getText().toString().trim());
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    if (result == 0) {
                                        Message msg = Message.obtain();
                                        msg.what = PAY_SUCCESS;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                    } else {
                        DBHelper db = new DBHelper(Recharge.this);
                        SQLiteDatabase sd = db.getWritableDatabase();
                        int userId = 0;
                        Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                        while (cursor.moveToNext()) {
                            userId = cursor.getInt(0);
                        }
                        cursor.close();
                        final int finalUserId = userId;
                        new Thread() {
                            @Override
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/myWalletAction/zhifubaoPaySuccess";
                                    final Map<String, String> map1 = new HashMap<String, String>();
                                    map1.put("userId", finalUserId + "");
                                    map1.put("moneyMunber", money_munber.getText().toString());
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    if (result == 0) {
                                        Message msg = Message.obtain();
                                        msg.what = PAY_SUCCESS;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(Recharge.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
                case SUCCESS: {

                }
                    break;
                case ERROR:{

                }
                    break;
                default:{

                }
                    break;
            }

        };
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //我的余额
            case R.id.money_zhifubao_pay:{
                if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
                    new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialoginterface, int i) {
                                    //
                                    finish();
                                }
                            }).show();
                    return;
                }

                boolean rsa21 = (RSA2_PRIVATE.length() > 0);
                Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa21);
                String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
                String privateKey1 = rsa21 ? RSA2_PRIVATE : RSA_PRIVATE;
                String sign1 = OrderInfoUtil2_0.getSign(params, privateKey1, rsa21);
                final String orderInfo = orderParam + "&" + "total_fee=0.01&" + sign1;
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(Recharge.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Log.i("msp", result.toString());
                        Log.v(tag, result + "");
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
                break;
            default:{

            }
                break;
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        View cv = getWindow().getDecorView();
        cv.setFocusableInTouchMode(true);
        cv.requestFocus();
        cv.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                    Intent intent = new Intent();
                    intent.setClass(Recharge.this, Money.class);
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
    }
}
